//
//  SystemLogin.swift
//  
//
//  Created by 孙长坦 on 2022/9/29.
//

import Foundation
import UIKit
import Logging
import AuthenticationServices

class SystemLogin: NSObject, LoginProtocol {
    static var type: String = "apple"
    
    private var logger = Logger(label: "SystemLogin")
    
    var name: String = "Apple"
    
    var icon: UIImage? = UIImage(named: "icon_login_system", in: Bundle.module, compatibleWith: nil)
    
    private var completion: Completion?
    
    required init(sdk: SDKProtocol) {
        
    }
    
    deinit {
        logger.info("SystemLogin deinit")
    }
    
    func login(completion: Completion?) {
        guard #available(iOS 13.0, *) else {
            completion?(false, "available iOS13", nil)
            return
        }
        
        self.completion = completion
        
        let request = ASAuthorizationAppleIDProvider().createRequest()
        request.requestedScopes = [ASAuthorization.Scope.email, ASAuthorization.Scope.fullName]
        
        let controller = ASAuthorizationController(authorizationRequests: [request])
        controller.delegate = self
        controller.presentationContextProvider = self
        controller.performRequests()
    }
}

@available(iOS 13.0, *)
extension SystemLogin: ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController,
                                 didCompleteWithAuthorization authorization: ASAuthorization) {
        guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else {
            completion?(false, nil, nil)
            return
        }
        
        guard let data = appleIDCredential.identityToken,
              let token = String(data: data, encoding: .utf8) else {
            completion?(false, nil, nil)
            return
        }
        
        let loginModel = LoginModel(code: appleIDCredential.user, token: token, nickName: nil, avatar: nil)
        completion?(true, nil, loginModel)
    }
    
    public func authorizationController(controller: ASAuthorizationController,
                                        didCompleteWithError error: Error) {
        completion?(false, error.localizedDescription, nil)
    }
}

@available(iOS 13.0, *)
extension SystemLogin: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIWindow.ex.key!
    }
}
